'use client';

import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Loader2, LogIn } from 'lucide-react';
import { AuthApi, clearTokenLocal, type MeResponse } from '@/lib/api';

function useOutsideClick(ref: { current: Element | null }, onClose: () => void) {
  useEffect(() => {
    function handler(e: MouseEvent) {
      if (!ref.current) return;
      if (!ref.current.contains(e.target as Node)) onClose();
    }
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [ref, onClose]);
}

export default function NavUser() {
  const [me, setMe] = useState<MeResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const popRef = useRef<HTMLDivElement>(null);
  useOutsideClick(popRef, () => setOpen(false));

  useEffect(() => {
    let mounted = true;
    (async () => {
      const res = await AuthApi.me();
      if (!mounted) return;
      if (res.ok) setMe(res.data);
      setLoading(false);
    })();
    return () => {
      mounted = false;
    };
  }, []);
  const blockOuterLink = loading || !!me;

  if (loading) {
    return (
      <div
        className="flex items-center"
        onMouseDown={(e) => {
          e.preventDefault();
          e.stopPropagation();
        }}
      >
        <Loader2 className="h-4 w-4 animate-spin text-fd-muted-foreground pointer-events-none" aria-label="loading" />
      </div>
    );
  }

  if (!me) {
    return (
      <div className="flex items-center">
        <span className="sr-only">登录</span>
        <LogIn
          className="h-4 w-4 text-fd-muted-foreground pointer-events-none"
          aria-hidden="true"
        />
      </div>
    );
  }

  const display = me.userName || me.email || '用户';

  return (
    <div
      className="relative"
      ref={popRef}
      onMouseDown={(e) => {
        if (blockOuterLink) {
          e.preventDefault();
          e.stopPropagation();
        }
      }}
    >
      <button
        type="button"
        className="flex items-center gap-2 rounded-full px-2 py-1 hover:bg-fd-accent"
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          setOpen((v) => !v);
        }}
        aria-haspopup="menu"
        aria-expanded={open}
      >
        <Avatar src={me.avatar} name={display} />
        <span className="hidden md:inline text-sm">{display}</span>
      </button>

      {open && (
        <div
          role="menu"
          className="absolute right-0 z-50 mt-2 w-56 rounded-md border bg-fd-popover text-fd-popover-foreground shadow-md"
        >
          <div className="px-4 py-3">
            <p className="text-sm font-medium">{display}</p>
            <p className="text-xs text-fd-muted-foreground truncate">{me.email}</p>
          </div>
          <div className="border-t" />
          <div className="p-1">
            <MenuItem href="/account/profile">编辑基本信息</MenuItem>
            <MenuItem href="/account/password">变更密码</MenuItem>
            <button
              className="w-full text-left rounded-sm px-3 py-2 text-sm hover:bg-fd-accent"
              onClick={() => {
                clearTokenLocal();
                window.location.href = '/';
              }}
            >
              退出登录
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function Avatar({ src, name }: { src?: string; name: string }) {
  if (src) {
    return (
      <Image
        src={src}
        alt={name}
        width={28}
        height={28}
        className="rounded-full object-cover"
        unoptimized
      />
    );
  }
  const initials =
    name
      .trim()
      .split(/\s+/)
      .map((s) => s[0])
      .join('')
      .slice(0, 2) || 'U';
  return (
    <div className="inline-flex h-7 w-7 items-center justify-center rounded-full bg-fd-muted text-xs font-medium">
      {initials}
    </div>
  );
}

function MenuItem({
  href,
  children,
}: {
  href: string;
  children: React.ReactNode;
}) {
  return (
    <Link
      href={href}
      className="flex w-full items-center rounded-sm px-3 py-2 text-sm hover:bg-fd-accent"
    >
      {children}
    </Link>
  );
}